//
//  LoginViewController.m
//  Meal4iOS
//
//  Created by Jaedong n.Die_ on 12-8-16.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "LoginViewController.h"

#import "Contants.h"
#import "MEALServices.h"
#import "GradientButton.h"
#import "StatusIndicatorHelper.h"

@interface LoginViewController ()


@end

@implementation LoginViewController

@synthesize delegate = _delegate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    // Set background color.
    CAGradientLayer *layer = [CAGradientLayer layer];
    layer.frame = CGRectMake(0.0f, 0.0f, kMaxFrameWidth, kMaxFrameHeight);
    layer.locations = [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.0f], [NSNumber numberWithFloat:1.0f], nil];
    layer.colors = [NSArray arrayWithObjects:(id)[[UIColor colorWithRed:252 / 255.0f green:252 / 255.0f blue:252 / 255.0f alpha:1.0f] CGColor],
                    (id)[[UIColor colorWithRed:222 / 255.0f green:222 / 255.0f blue:208 / 255.0f alpha:1.0f] CGColor], nil];
    [self.view.layer addSublayer:layer];
    
    UIImage *tileImage = [UIImage imageNamed:@"Noise.png"];
    int nXTileCount = ceilf(kMaxFrameWidth / tileImage.size.width);
    int nYTitleCount = ceilf(kMaxFrameHeight / tileImage.size.height);
    
    UIImageView *tileImageView = nil;
    for (int i = 0; i < nXTileCount; i++) {
        for (int j = 0; j < nYTitleCount; j++) {
            
            tileImageView = [[UIImageView alloc] initWithImage:tileImage];
            tileImageView.frame = CGRectMake(i * tileImage.size.width, j * tileImage.size.height, tileImage.size.width, tileImage.size.height);
            [self.view addSubview:tileImageView];
            [tileImageView release];
        }
    }
    
    // Set input view background view.
    _inputBackgroundView = [[UIView alloc] initWithFrame:CGRectMake(312.0f, 140.0f, 400.0f, 200.0f)];
    _inputBackgroundView.userInteractionEnabled = YES;
    _inputBackgroundView.layer.shadowColor = [UIColor blackColor].CGColor;
    _inputBackgroundView.layer.shadowOffset = CGSizeMake(2, 5);
    _inputBackgroundView.layer.shadowOpacity = 0.5;
    [self.view addSubview:_inputBackgroundView];
    [_inputBackgroundView release];
    
    CAGradientLayer *backgroundLayer = [CAGradientLayer layer];
    backgroundLayer.cornerRadius = 10.0f;
    backgroundLayer.frame = _inputBackgroundView.bounds;
    backgroundLayer.locations = [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.0f], [NSNumber numberWithFloat:1.0f], nil];
    backgroundLayer.colors = [NSArray arrayWithObjects:(id)[[UIColor colorWithRed:134 / 255.0f green:228 / 255.0f blue:0.0f alpha:1.0f] CGColor],
                              (id)[[UIColor colorWithRed:73 / 255.0f green:138 / 255.0f blue:0.0f alpha:1.0f] CGColor], nil];
    [_inputBackgroundView.layer addSublayer:backgroundLayer];
    
    // Init text fields.
    _userField = [[UITextField alloc] initWithFrame:CGRectMake(20.0f, 20.0f, 360.0f, 40.0f)];
    _userField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _userField.placeholder = @"请输入用户名";
    _userField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _userField.backgroundColor = [UIColor whiteColor];
    _userField.layer.cornerRadius = 5.0f;
    _userField.returnKeyType = UIReturnKeyNext;
    _userField.delegate = self;
    [_inputBackgroundView addSubview:_userField];
    [_userField release];
    
    _pwdField = [[UITextField alloc] initWithFrame:CGRectMake(20.0f, 80.0f, 360.0f, 40.0f)];
    _pwdField.keyboardType = UIKeyboardTypeNumberPad;
    _pwdField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _pwdField.placeholder = @"请输入密码";
    _pwdField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _pwdField.backgroundColor = [UIColor whiteColor];
    _pwdField.layer.cornerRadius = 5.0f;
    _pwdField.returnKeyType = UIReturnKeyDone;
    _pwdField.delegate = self;
    [_inputBackgroundView addSubview:_pwdField];
    [_pwdField release];
    
    _loginButton = [GradientButton buttonWithType:UIButtonTypeCustom];
    _loginButton.frame = CGRectMake(20.0f, 140.0f, 360.0f, 40.0f);
    _loginButton.titleLabel.font = [UIFont boldSystemFontOfSize:25.0f];
    _loginButton.layer.cornerRadius = 5.0f;
    [_loginButton setTitle:@"登      陆" forState:UIControlStateNormal];
    [_loginButton addTarget:self action:@selector(clickLoginEvent:) forControlEvents:UIControlEventTouchUpInside];
    [_inputBackgroundView addSubview:_loginButton];
}

- (void)viewDidAppear:(BOOL)animated {

    [super viewDidAppear: animated];
    
    [_userField becomeFirstResponder];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    if(_userField != nil) {
    
        [_userField resignFirstResponder];
    }
    
    if(_pwdField != nil) {
    
        [_pwdField resignFirstResponder];
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIDeviceOrientationLandscapeRight);
}

- (void)dealloc {

    [super dealloc];
}

#pragma mark -
#pragma mark Action Support.

- (void)clickLoginEvent:(id)sender {
    
    if(_userField.text.length == 0) {
    
        alertInfo(@"用户名不可为空!");
        return;
    }
    
    if(_pwdField.text.length == 0) {
    
        alertInfo(@"密码不可为空!");
        return;
    }
    
    [StatusIndicatorHelper showIndicatorInView:_inputBackgroundView withText:@"验证用户中..."];
    
    MEALServices *services = [MEALServices service];
    [services.meal Login:self userName:_userField.text psw:_pwdField.text];	
}

#pragma mark -
#pragma UITextFieldDelegate Support.

- (BOOL)textFieldShouldReturn:(UITextField *)textField {

    if(textField == _userField) {
    
        [_pwdField becomeFirstResponder];
    }else if(textField == _pwdField) {
    
        [_pwdField resignFirstResponder];
        
        [self clickLoginEvent:nil];
    }
    
    return YES;
}

#pragma mark -
#pragma mark SoapDelegate Support.

- (void)onload:(id)value {

    [StatusIndicatorHelper hiddenIndicatorInView:_inputBackgroundView];
    
    BOOL result = [((NSNumber *)value) boolValue];
    if(!result) {
    
        alertInfo(@"用户名或密码错误!");
        return;
    }else {
    
        if(_delegate != nil && [_delegate respondsToSelector:@selector(loginDidSuccess)]) {
        
            [_delegate loginDidSuccess];
        }
    }
}

- (void)onerror:(NSError*)error {
    
    [StatusIndicatorHelper hiddenIndicatorInView:_inputBackgroundView];

    if(error.code == 400) {
    
        alertInfo(@"网络连接失败,请检查网络!");
    }else if(error.code == 401) {
    
        alertInfo(@"服务器连接失败,请联系管理员!");
    }
}

@end
